package com.spring.demo.untils.document.handle;

import com.spring.demo.untils.document.OrderMapping;
import com.spring.demo.untils.document.config.GlobalConfig;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuweizhi
 * @since 2023/04/26 11:27
 */
@Data
public class SqlMapping implements OutputHandle<String> {

    private GlobalConfig globalConfig;

    private String sqlTemplate;

    private List<OrderMapping> orderMapping;


    private List<String> sqlTemplates = new ArrayList<>();

    public SqlMapping(GlobalConfig globalConfig, String sqlTemplate, List<OrderMapping> orderMapping) {
        this.globalConfig = globalConfig;
        this.sqlTemplate = sqlTemplate;
        this.orderMapping = orderMapping;
    }

    @Override
    public String handle(String line) {

        String[] split = line.split(globalConfig.getSplit());

        String resultStr = sqlTemplate;

        orderMapping.sort(OrderMapping::compareTo);

        List<String> collect = orderMapping.stream().map(orderMapping1 -> {
            if (orderMapping1.getRelationKeyIndex() != null) {
                // return (String) orderMapping.get().apply(split);
                return null;
            }
            return split[orderMapping1.getValueIndex()];
        }).toList();

        sqlTemplates.add(String.format(resultStr, collect.toArray(new Object[2])));
        return resultStr;
    }
}
